import { createRouter, createWebHistory } from "vue-router";
import axios from "axios";
import { ElMessage } from "element-plus";
import { useUserStore } from "@/stores/user";

// 懒加载组件
const Login = () => import("@/views/login/Login.vue");
const Layout = () => import("@/layout/Layout.vue");

export const routes = [
  {
    path: "/login",
    name: "Login",
    component: Login,
    meta: { title: "登录" },
  },
  {
    path: "/register",
    name: "Register",
    component: () => import("@/views/user/Register.vue"),
    meta: { title: "注册" },
  },
  {
    path: "/",
    component: Layout,
    children: [
      {
        path: "dashboard",
        name: "Dashboard",
        meta: { title: "首页", icon: "HomeFilled" },
        component: () => import("@/views/dashboard/Index.vue"),
      },
      {
        path: "/admin",
        name: "AdminPage",
        meta: { title: "管理员页", icon: "UserFilled", roles: ["admin"] },
        component: () => import("@/views/admin/Index.vue"),
      },
      {
        path: "/user",
        name: "UserManage",
        meta: { title: "用户管理", icon: "User" },
        component: () => import("@/views/user/Index.vue"),
      },
      {
        path: "/activity",
        name: "ActivityConfig",
        meta: { title: "活动配置", icon: "Setting" },
        component: () => import("@/views/activity/Index.vue"),
      },
      {
        path: "/screen",
        name: "ScreenPanel",
        meta: { title: "大屏展示", icon: "Monitor" },
        component: () => import("@/views/screen/Index.vue"),
      },
      {
        path: "technicalDifficulties",
        name: "TechnicalDifficulties",
        meta: { title: "小难点", icon: "Monitor" },
        children: [
          {
            path: "BigFileUpload",
            name: "DifficultyOne",
            meta: { title: "大文件上传" },
            component: () =>
              import("@/views/technicalDifficulties/BigFileUpload.vue"),
          },
          {
            path: "VirtualList",
            name: "DifficultyTwo",
            meta: { title: "虚拟列表" },
            component: () =>
              import(
                "@/views/technicalDifficulties/VirtualList/VirtualList.vue"
              ),
          },
          {
            path: "refAndReactive",
            name: "DifficultyThree",
            meta: { title: "ref和reactive" },
            component: () =>
              import(
                "@/views/technicalDifficulties/refAndReactive/refAndReactive.vue"
              ),
          },
          {
            path: "diff",
            name: "diff",
            meta: { title: "diff算法对比" },
            component: () =>
              import("@/views/technicalDifficulties/vue2&vue3/diff.vue"),
          },
          {
            path: "TablePanel",
            name: "TablePanel",
            meta: { title: "封装TablePanel组件" },
            component: () =>
              import("@/views/technicalDifficulties/TablePanel.vue"),
          },
           {
            path: "Cascader",
            name: "Cascader",
            meta: { title: "封装Cascader组件" },
            component: () =>
              import("@/views/technicalDifficulties/Cascader/demo.vue"),
          },
        ],
      },
      {
        path: "/frontendSecurity",
        name: "FrontendSecurity",
        meta: { title: "前端安全", icon: "Monitor" },
        children: [
          {
            path: "XXS",
            name: "XXS",
            meta: { title: "XXS" },
            component: () => import("@/views/FrontendSecurity/XXS.vue"),
          },
          {
            path: "csrfLab",
            name: "CsrfLab",
            meta: { title: "CSRF实验室" },
            component: () => import("@/views/FrontendSecurity/CsrfLab.vue"),
          },
        ],
      },
      {
        path: "ComplexForms",
        name: "ComplexForms",
        meta: { title: "复杂表单" },
        children: [
          {
            path: "DynamicForm",
            name: "DynamicForm",
            meta: { title: "动态表单" },
            component: () => import("@/views/ComplexForms/DynamicForm.vue"),
          },
          {
            path: "SchemaForm",
            name: "SchemaForm",
            meta: { title: "Schema驱动表单" },
            component: () =>
              import("@/views/ComplexForms/SchemaForm/index.vue"),
          },
        ],
      },
      {
        path: "/model/viewer",
        name: "ModelViewer",
        component: () => import("@/views/model/ModelViewer.vue"),
        meta: { title: "模型预览" },
      },
      {
        path: "/learnThree",
        name: "LearnThree",
        meta: { title: "学习Three.js" },
        children: [
          {
            path: "day1",
            name: "day1",
            meta: { title: "第一天" },
            component: () => import("@/views/learnThree/day1.vue"),
          },
          {
            path: "day2",
            name: "day2",
            meta: { title: "第二天" },
            component: () => import("@/views/learnThree/day2.vue"),
          },
          {
            path: "day3",
            name: "day3",
            meta: { title: "第三天" },
            component: () => import("@/views/learnThree/day3.vue"),
          },
          {
            path: "day4-1",
            name: "day4-1",
            meta: { title: "第四天-光照系统" },
            component: () => import("@/views/learnThree/day4-1.vue"),
          },
          {
            path: "day4-2",
            name: "day4-2",
            meta: { title: "第四天-光照系统-动态调整" },
            component: () => import("@/views/learnThree/day4-2.vue"),
          },
          {
            path: "comparisonMaterial",
            name: "comparisonMaterial",
            meta: { title: "材质类型对比 Demo" },
            component: () =>
              import("@/views/learnThree/comparisonMaterial.vue"),
          },
          {
            path: "cameraControl",
            name: "cameraControl",
            meta: { title: "相机控制 Demo" },
            component: () => import("@/views/learnThree/cameraControl.vue"),
          },
        ],
      },
      {
        path: "/Metro3D",
        name: "Metro3D",
        meta: { title: "广州地铁线路" },
        children: [
          {
            path: "Metro3DDemo1",
            name: "Metro3D-Demo1",
            meta: { title: "Demo1" },
            component: () => import("@/views/Metro3D/Metro3DDemo1.vue"),
          },
          {
            path: "Metro3DDemo2",
            name: "Metro3D-Demo2",
            meta: { title: "Demo2" },
            component: () => import("@/views/Metro3D/Metro3DDemo2.vue"),
          },
          {
            path: "Metro3DDemo3",
            name: "Metro3D-Demo3",
            meta: { title: "Demo3" },
            component: () => import("@/views/Metro3D/Metro3DDemo3.vue"),
          },
          {
            path: "GroundFootprintDemo",
            name: "GroundFootprintDemo",
            meta: { title: "理解GroundFootprintDemo" },
            component: () =>
              import("@/views/Metro3D/demo/GroundFootprintDemo.vue"),
          },
        ],
      },
      {
        path: "/3DProject",
        name: "3DProject",
        meta: { title: "3D项目" },
        children: [
          {
            path: "tollStation",
            name: "tollStation",
            meta: { title: "收费站" },
            component: () => import("@/views/3DProject/tollStation/index.vue"),
          },
        ],
      },
    ],
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

const whiteList = ["/login", "/register"]; // 无需登录即可访问的路径

router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore();
  const accessToken = localStorage.getItem("accessToken");
  const refreshToken = localStorage.getItem("refreshToken");
  // 设置页面标题
  if (to.meta.title) document.title = to.meta.title;

  // 白名单页面直接放行
  if (whiteList.includes(to.path)) {
    return next();
  }

  // 有 accessToken，尝试正常访问
  if (accessToken) {
    return next();
  }

  // accessToken 没有，但存在 refreshToken，尝试刷新
  if (refreshToken) {
    try {
      const res = await axios.post("/api/user/refresh-token", { refreshToken });
      if (res.data.code === 0) {
        localStorage.setItem("accessToken", res.data.data.accessToken);
        return next(); // 刷新成功继续访问
      } else {
        throw new Error("refresh 失败");
      }
    } catch (err) {
      ElMessage.error("登录已过期，请重新登录:路由");
      localStorage.removeItem("accessToken");
      localStorage.removeItem("refreshToken");
      return next("/login");
    }
  }
  // const role = userStore.userInfo?.role;

  // if (to.meta?.roles && !to.meta.roles.includes(role)) {
  //   return next("/dashboard"); // 没权限跳回首页
  // }
  // next();
  // 没有 token，跳转登录
  return next("/login");
});

export default router;
